package com.sub.project.minio;

import com.sub.common.utils.minio.MinioEntity;
import com.sub.framework.web.domain.AjaxResult;
import io.minio.MinioClient;
import io.minio.PutObjectOptions;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
@RequestMapping("minio")
public class MinioController {
    private static final Logger LOGGER = LoggerFactory.getLogger(MinioController.class);
    @Value("${minio.endpoint}")
    private String ENDPOINT;
    @Value("${minio.bucketName}")
    private String BUCKET_NAME;
    @Value("${minio.accessKey}")
    private String ACCESS_KEY;
    @Value("${minio.secretKey}")
    private String SECRET_KEY;

    @ApiOperation("文件上传")
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public AjaxResult upload(@RequestParam("file") MultipartFile file) {
        try {
            //创建一个MinIO的Java客户端
            MinioClient minioClient = new MinioClient(ENDPOINT, ACCESS_KEY, SECRET_KEY);
            boolean isExist = minioClient.bucketExists(BUCKET_NAME);
            if (isExist) {
                LOGGER.info("存储桶已经存在！");
            } else {
                //创建存储桶并设置只读权限
                minioClient.makeBucket(BUCKET_NAME);
                minioClient.setBucketPolicy(BUCKET_NAME, "*.*");
            }
            String filename = file.getOriginalFilename();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            // 设置存储对象名称
            String objectName = sdf.format(new Date()) + "/" + filename;
            // 使用putObject上传一个文件到存储桶中
            PutObjectOptions putObjectOptions = new PutObjectOptions(file.getSize(),-1l);
            putObjectOptions.setContentType(file.getContentType());
            minioClient.putObject(BUCKET_NAME, objectName, file.getInputStream(), putObjectOptions);
            LOGGER.info("文件上传成功!");
            MinioEntity minioUploadDto = new MinioEntity();
            minioUploadDto.setObjectName(filename);
            minioUploadDto.setEtag(ENDPOINT + "/" + BUCKET_NAME + "/" + objectName);
            minioUploadDto.setLastModified(new Date());
            minioUploadDto.setSize(file.getSize());
            return AjaxResult.success(minioUploadDto);
        } catch (Exception e) {
            LOGGER.info("上传发生错误: {}！", e.getMessage());
        }
        return AjaxResult.error();
    }
    
    @ApiOperation("文件删除")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult delete(@RequestParam("objectName") String objectName) {
        try {
            MinioClient minioClient = new MinioClient(ENDPOINT, ACCESS_KEY, SECRET_KEY);
            minioClient.removeObject(BUCKET_NAME, objectName);
            return AjaxResult.success(null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.error();
    }
}
